<?php
App::uses('AppModel', 'Model');

class Category extends AppModel {

    public $order = 'Category.position';

	public $hasMany = array(
		'Product' => array(
			'className' => 'Product',
			'foreignKey' => 'category_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		),
		'SubCategory' => array(
		  'className'  => 'Category',
		  'foreignKey' => 'parent_id'
        )
	);
    public $belongsTo = array(
        'ParentCategory' => array(
            'className'  => 'Category',
            'foreignKey' => 'parent_id'
        )
    );
    
    public $validate = array(
        'name' => array(
            'rule'    => 'notEmpty',
            'message' => 'Morate uneti naziv kategorije.'
        )
    );
	
	public function beforeDelete($cascade = true) {
		parent::beforeDelete($cascade);
		
		if($this->id) {
			$image = $this->field('image', array('id'=>$this->id));
			@unlink('img' . DS . 'categories' . DS . $image);
		}
		
		return true;
	}
    
    public function tree($parent_id = null) {
        $categories = $this->find('all', array(
            'conditions' => array( 'Category.parent_id' => $parent_id),
            'recursive'  => 0
        ));
        foreach ($categories as &$category) {
            $category['children'] = $this->tree($category['Category']['id']);
        }
        return $categories;
    }

}
